import {
	HOST
} from '@/config'
import {
	qs
} from '@/utils/tools'
import app from '@/main'
import {
	smallLogin
} from '@/api/public.js'
// import store from '@/store'
export default {
	install: function(Vue) {
		Vue.mixin({
			onLoad() {},
			methods: {
				back(index) {
					uni.navigateBack({
						delta: index || 1,
						fail() {
							uni.redirectTo({
								url: '/pages/main/mine'
							})
						}
					})
				},
				routerLink(obj, isLogin, cd) {
					// 页面需要登录授权
					if (isLogin) {
						const userStore = this.$store.state.user
						// 没有授权
						if (!userStore.token) {
							this.thirdLogin(obj, cd)
						} else {
							if (!userStore.userInfo.phone) {
								// 去获取手机号
								uni.navigateTo({
									url: '/pages/user/login/index'
								})
							} else {
								if (obj.path) {
									uni[obj.openType || 'navigateTo'](qs(Object.assign({
										url: obj.path
									}, obj.query || {})))
								} else {
									cd && cd()
								}
							}
						}
					} else {
						if (obj.path) {
							uni[obj.openType || 'navigateTo'](qs(Object.assign({
								url: obj.path
							}, obj.query || {})))
						}
					}
				},

				// 第三方授权登录
				async thirdLogin(obj, cd) {
					const [err, info] = await uni.getUserProfile({
						desc: '用于完善会员资料'
					})
					console.log('info====', info);
					console.log(err, info)
					if (!info || info.errMsg !== 'getUserProfile:ok') {
						return false
					}
					const [a, {
						code,
						errMsg
					}] = await uni.login()

					if (errMsg !== 'login:ok') {
						return false
					}
					const wxAppId = uni.getAccountInfoSync().miniProgram.appId
					const res = await smallLogin({
						wxCode: code,
						wxAppId,
						encryptedData: '',
						iv: '',
						nickName: '微信用户',
						// gender: info.userInfo.gender, // 性别 1男 2女
						headImgUrl: ''
					})

					this.$store.commit('login', res.data)
					// this.$store.commit('setThirdInfo', res.data.thirdinfo)
					await this.$store.dispatch('getUserInfo')
					// 用户没有授权手机号
					if (!(this.$store.state.user.userInfo && this.$store.state.user.userInfo.phone)) {
						uni.navigateTo({
							url: '/pages/user/login/index'
						})
					} else {
						if (obj.path) {
							uni[obj.openType || 'navigateTo'](qs(Object.assign({
								url: obj.path
							}, obj.query || {})))
						} else {
							cd && cd()
						}
					}
				},
				toast(title, keep) {
					uni.showToast({
						icon: 'none',
						title: title,
						mask: true,
						duration: keep || 2000
					});
				},
				showLoading(title) {
					uni.showLoading({
						title: title || '请稍候...',
						// #ifdef MP-WEIXIN
						mask: true
						// #endif
					});
				},
				async confirm({
					title = '提示',
					content = '',
					confirmColor = '#3282FF',
					cancelColor = '#000000',
					cancelText = '取消',
					confirmText = '确定',
					showCancel = true
				} = {}) {
					let [err, res] = await uni.showModal({
						title: title,
						content: content || '操作成功!',
						confirmColor: confirmColor,
						cancelColor: cancelColor,
						cancelText: cancelText,
						confirmText: confirmText,
						showCancel: showCancel
					});
					return res;
				},
				jsonGet(obj) {
					let o = {},
						attr = Array.prototype.slice.call(arguments).slice(1);

					attr.forEach(function(val, index) {
						if (val in obj) {
							o[val] = obj[val];
						}
					});
					return o;
				},
				// 微信支付
				wx_payment(params, cd) {
					console.log('微信支付接口', params)
					// 调起微信支付
					// const _self = this
					uni.requestPayment({
						// 正常的
						appId: params.appId,
						nonceStr: params.nonceStr,
						package: params.package,
						paySign: params.paySign,
						signType: params.signType,
						timeStamp: params.timeStamp,

						// 拉卡拉
						// appId: params.app_id,
						// nonceStr: params.nonce_str,
						// package: params.package,
						// paySign: params.pay_sign,
						// signType: params.sign_type,
						// timeStamp: params.time_stamp,
						success: e => {
							console.log(e)
							console.log('微信支付成功')
							cd && cd(1)
						},
						fail: err => {
							console.log('微信支付失败')
							console.log(err)
							cd && cd(2)

						}
					})
				},
				delay(timeout = 2000) {
					return new Promise(resolve => {
						setTimeout(resolve, timeout);
					});
				},
				call(mobile) {
					if (mobile) {
						uni.makePhoneCall({
							phoneNumber: mobile + ''
						})
					}
				},
				formatImg(url, defaultImg) {
					console.log(url)
					if (url) return url.startsWith('http') ? url : HOST + '/' + url
					else return defaultImg ? defaultImg : '/static/defaultImg.png'
				},
				getUrlParam(name, url) {
					let param = url.substr(url.indexOf('?') + 1);
					var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
					var r = param.match(reg);
					if (r != null) return unescape(r[2]);
					return '';
				},
				previewImage(url, list) {
					url = this.formatImg(url);
					list = list.map(item => this.formatImg(item))
					uni.previewImage({
						current: url, // 当前显示图片的http链接
						urls: list, // 需要预览的图片http链接列表
						success: function(res) {
							console.log(res);
						}
					});
				},
			}
		})
		Vue.filter('formatImg', function(url, defaultImg) {
			if (url) return url.startsWith('http') ? url : HOST + '/' + url;
			else return defaultImg ? defaultImg : '/static/defaultImg.png';
		});
		Vue.filter('formatTime', function(time, format = 'Y-M-D h:m:s') {

			if (!time) return time || '--';

			if ((typeof time == String) && time.indexOf('T') > 0) {
				time = new Date(time).getTime();
			}
			if (Number(time).toString().length == 10) {
				time = Number(time + "000")
			}
			time = new Date(time);

			function formatNumber(n) {
				n = n.toString()
				return n[1] ? n : '0' + n
			}
			const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
			const returnArr = [];

			returnArr.push(time.getFullYear());
			returnArr.push(formatNumber(time.getMonth() + 1));
			returnArr.push(formatNumber(time.getDate()));

			returnArr.push(formatNumber(time.getHours()));
			returnArr.push(formatNumber(time.getMinutes()));
			returnArr.push(formatNumber(time.getSeconds()));

			for (var i in returnArr) {
				format = format.replace(formateArr[i], returnArr[i]);
			}
			return format;
		})
		// 日期斜杠标志
		// Vue.filter('formatTime2', function(time, format = 'Y/M/D h:m:s') {

		// 	if (!time) return time || '--';

		// 	if ((typeof time == String) && time.indexOf('T') > 0) {
		// 		time = new Date(time).getTime();
		// 	}
		// 	if (Number(time).toString().length == 10) {
		// 		time = Number(time + "000")
		// 	}
		// 	time = new Date(time);

		// 	function formatNumber(n) {
		// 		n = n.toString()
		// 		return n[1] ? n : '0' + n
		// 	}
		// 	const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
		// 	const returnArr = [];

		// 	returnArr.push(time.getFullYear());
		// 	returnArr.push(formatNumber(time.getMonth() + 1));
		// 	returnArr.push(formatNumber(time.getDate()));

		// 	returnArr.push(formatNumber(time.getHours()));
		// 	returnArr.push(formatNumber(time.getMinutes()));
		// 	returnArr.push(formatNumber(time.getSeconds()));

		// 	for (var i in returnArr) {
		// 		format = format.replace(formateArr[i], returnArr[i]);
		// 	}
		// 	return format;
		// })

		Vue.filter('fixedTo', function(val, num) {
			return val ? val.toFixed(num) : 0;
		});
	}
}